//合并 k 个排序链表，返回合并后的排序链表。请分析和描述算法的复杂度。 
//
// 示例: 
//
// 输入:
//[
//  1->4->5,
//  1->3->4,
//  2->6
//]
//输出: 1->1->2->3->4->4->5->6 
// Related Topics 堆 链表 分治算法

  
package com.gule.gl.leetcode.editor.cn;

import java.util.Objects;

public class MergeKSortedLists{
    public static void main(String[] args) {
         Solution solution = new MergeKSortedLists().new Solution();

    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(Objects.isNull(lists) || lists.length ==0){
            return null;
        }
        int len = lists.length;
        while(len >1) {
            for (int i = 0; i < len / 2 ; i++) {
                lists[i] = mergeTwoList(lists[i], lists[len - 1 - i]);
            }
            len = (len+1) / 2;
        }
        return lists[0];
    }

    private ListNode mergeTwoList(ListNode list1, ListNode list2) {
        ListNode guardNode = new ListNode(-1);
        ListNode tmp = guardNode;
        while (Objects.nonNull(list1) && Objects.nonNull(list2)){
            if(list1.val < list2.val){
                tmp.next = list1;
                list1 = list1.next;
            }else{
                tmp.next = list2;
                list2 = list2.next;
            }
            tmp = tmp.next;
        }
        if(Objects.nonNull(list1)){
            tmp.next = list1;
        }
        if(Objects.nonNull(list2)){
            tmp.next = list2;
        }
        return guardNode.next;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
    public class ListNode{
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}
